package com.quwan.common;

import com.quwan.common.exception.ExpCode;
import com.quwan.common.exception.ResponseException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.persistence.Id;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author quan
 * @date 2021-06-07 17:27
 */

public abstract class BaseController {
    protected Logger logger = LoggerFactory.getLogger(getClass());
    private static int PageSizeMinValue = 1;
    private static int PageSizeMaxValue = 100;

    protected void checkPageSize(int pageSize) {
        boolean ret = pageSize < PageSizeMinValue || pageSize > PageSizeMaxValue;
        if (ret) {
            throw new RuntimeException(String.format("Invalid param [%s]", pageSize));
        }
    }


    protected String getId(HttpServletRequest request) {
        String id = getRequestAttr(request).get("userId");
        if (StringUtils.isBlank(id))
            throw new ResponseException(ExpCode.NEED_LOGIN.getCode(), ExpCode.NEED_LOGIN.getMsg());
        return id;
    }

    protected String checkMemberId(HttpServletRequest request, String mId) {
        String res = StringUtils.isNotBlank(mId) ?
                "undefined".equalsIgnoreCase(mId) ?
                        getTokenInfo(request).getId()
                        : mId
                : getTokenInfo(request).getId();
        if (StringUtils.isBlank(res)) throw new IllegalArgumentException("member Id is null");
        return res;
    }

    protected TokenInfo getTokenInfo(HttpServletRequest request) {
        Map<String, String> attr = getRequestAttr(request);
        return new TokenInfo(attr.get("userId"), attr.get("username"));
    }


    private Map<String, String> getRequestAttr(HttpServletRequest request) {
        Map<String, String> map = new HashMap<>();
        Enumeration<?> temp = request.getAttributeNames();
        if (null != temp) {
            while (temp.hasMoreElements()) {
                String en = (String) temp.nextElement();
                String value = request.getAttribute(en).toString();
                map.put(en, value);
            }
        }
        return map;
    }

    public class TokenInfo {
        private String id;
        private String username;

        public TokenInfo(String id, String username) {
            this.id = id;
            this.username = username;

        }


        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getUsername() {
            return username;
        }

        public void setUsername(String mobile) {
            this.username = mobile;
        }
    }
}
